package cn.lan.code.controller;

import cn.hutool.core.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.stereotype.Controller;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

/**
 * 基础工具控制器
 * @author lanping
 * @version 1.0
 * @date 2021-11-02
 */
@ApiIgnore
@Controller
public class BaseController {

	private Logger logger = LoggerFactory.getLogger(BaseController.class);

	/**
	 * 初始化request
	 */
	protected Map<String, Object> initRequestMap(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String,String[]> params = request.getParameterMap();
		if(params != null) {
			for(Entry<String,String[]> entry:params.entrySet()){
				String key = entry.getKey();
				String [] value = entry.getValue();
				if(StrUtil.isNotBlank(key)
					&& value != null && value.length > 0) {
					if(StrUtil.isNotBlank(value[0])){
						map.put(key, value[0]);
					}
				}
			}
		}
		return map;
	}

	/**
	 * @param response
	 * @param data
	 * @param contentType json格式： application/json;charset=UTF-8
	 *                    html：text/html;charset=UTF-8
	 */
	public void output(HttpServletResponse response, String data, String contentType) {
		try {
			response.setCharacterEncoding("utf-8");
			response.setContentType(contentType);
			PrintWriter out = response.getWriter();
			out.print(data);
			out.flush();
			out.close();
		} catch (IOException e) {
			logger.error("BaseController output error",e);
		}
	}
	
}
